package com.ealen.service;

import org.quartz.Scheduler;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

@Service
public class SchedulerRestartService {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private JobFactory jobFactory;
    @Autowired
    private DynamicJobService jobService;

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    /**
     * 安全重启调度器
     */
    public SchedulerFactoryBean restartScheduler() throws Exception {
        Scheduler  scheduler = schedulerFactoryBean.getScheduler();
        // 如何表中线程数量与原线程数量不同 则修改scheduler的线程数量
        Integer id = jobService.loadJobs().get(0).getId();
        System.out.println("2222原scheduler线程数量 " + scheduler.getMetaData().getThreadPoolSize());
        System.out.println("2222表中线程数量 " + id);
        if (scheduler.getMetaData().getThreadPoolSize() != id) {
            // 原调度器已安全关闭
            shutdownSchedulerGracefully();
            // 创建新的调度器
            schedulerFactoryBean = createAndStartNewScheduler();
            scheduler = schedulerFactoryBean.getScheduler();
            System.out.println("2222新scheduler线程数量 " + scheduler.getMetaData().getThreadPoolSize());
        } else {
            System.out.println("线程数量相同，无需重启");
        }
        return schedulerFactoryBean;
    }

    private void shutdownSchedulerGracefully() {
        if (schedulerFactoryBean != null) {
            try {
                //关闭调度器
                schedulerFactoryBean.getScheduler().shutdown(true);
                // 等待正在执行的任务完成:cite[1]
                schedulerFactoryBean.destroy();
                System.out.println("原调度器已安全关闭");
            } catch (Exception e) {
                System.err.println("关闭调度器时发生错误: " + e.getMessage());
            }
        }
    }

    public SchedulerFactoryBean createAndStartNewScheduler() throws Exception {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        //可选,QuartzScheduler启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        schedulerFactoryBean.setAutoStartup(false); //设置不自行启动
        schedulerFactoryBean.setDataSource(dataSource);
        schedulerFactoryBean.setJobFactory(jobFactory);
        schedulerFactoryBean.setQuartzProperties(quartzProperties());
        schedulerFactoryBean.afterPropertiesSet();      // ← 别忘了

        // 初始化并启动
        schedulerFactoryBean.start();
        return schedulerFactoryBean;
    }

    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
//        return propertiesFactoryBean.getObject();

//        启动时修改数据库表的线程数量ok
        Properties quartzProperties = propertiesFactoryBean.getObject();

        Integer id = jobService.loadJobs().get(0).getId();
        System.out.println("org.quartz.threadPool.1111threadCount= " + id);
        quartzProperties.setProperty("org.quartz.threadPool.threadCount", String.valueOf(id));
        return quartzProperties;
    }

    /**
     * 获取当前调度器实例
     */
    public Scheduler getNewScheduler() {
        return schedulerFactoryBean != null ? schedulerFactoryBean.getScheduler() : null;
    }
}

